import { useEffect, useRef, useState } from 'react';
import { Card, Button, Checkbox, Form, Input, Tooltip, message } from 'antd';
import {
  GlobalOutlined,
  QuestionCircleOutlined,
  CheckOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import { useTranslation } from 'react-i18next';

import { setIpConfig, getNetworkinfo } from "@/api/web";
import './index.scss';

// 常量提取
const DEFAULT_NETWORK_INFO = {
  gateway: "192.168.10.1",
  interface: "eth0",
  ip_address: "",
  netmask: "255.255.255.0"
};

function Web() {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const [info, setInfo] = useState(DEFAULT_NETWORK_INFO);
  const [dhcpEnabled, setDhcpEnabled] = useState(false);

  useEffect(() => {
    getLoad();
  }, []);

  function getLoad() {
    getNetworkinfo().then(res => {
      setInfo(res);
    });
  }

  function onFinish(values) {
    const param = values;
    // 如果启用了 DHCP，直接提交不验证
    if (param.dhcpEnabled) {
      submitForm(param);
    } else {
      // 非DHCP模式，正常验证并提交
      form.validateFields().then(() => {
        submitForm(param);
      });
    }
  }

  function submitForm(param) {
    const formData = new FormData();

    formData.append('new_ip', param.dhcpEnabled ? '' : (param.new_ip || ''));
    formData.append('new_mask', param.dhcpEnabled ? '' : (param.new_mask || ''));
    formData.append('router_ip', param.dhcpEnabled ? '' : (param.router_ip || ''));

    if (param.dhcpEnabled) {
      formData.append('dhcp', 'on');
    }

    setIpConfig(formData).then(res => {
      message.success(t('message.web.restart'));
    }).catch(error => {
      message.error(error.message);
    });
  }

  function onReset() {
    form.resetFields();
    setDhcpEnabled(false);
  }

  function handleDhcpChange(e) {
    setDhcpEnabled(e.target.checked);
  }

  // 渲染工具函数
  const renderCardTitle = (icon, titleKey) => (
    <div className='title'>
      {icon}
      <span className="tit">{t(titleKey)}</span>
    </div>
  );

  const renderLabelWithTooltip = (labelKey, tooltipKey) => (
    <div className="label-with-tooltip">
      <span className="item-tit">{t(labelKey)}</span>
      <Tooltip title={t(tooltipKey)}>
        <QuestionCircleOutlined style={{ color: '#3498db', marginLeft: 4 }} />
      </Tooltip>
    </div>
  );

  return (
    <div className="web-container">
      <div className="row-a1">
        <div className="left">
          <div className="con-a1">
            <Card
              title={renderCardTitle(
                <GlobalOutlined style={{ color: '#08c' }} />,
                'web.networkConfig'
              )}
            >
              <Form
                form={form}
                layout="vertical"
                name="form"
                autoComplete="off"
                initialValues={{ dhcpEnabled: false }}
                onFinish={onFinish}
              >
                <Form.Item
                  label={renderLabelWithTooltip('web.ipAddress', 'web.enterValidIPv4')}
                  name="new_ip"
                  rules={dhcpEnabled ? [] : [
                    {
                      required: true,
                      message: t('web.enterIP'),
                    },
                  ]}
                  extra={t('web.example') + ": 192.168.10.10"}
                >
                  <Input
                    placeholder={t('web.eg') + ": 192.168.10.10"}
                  />
                </Form.Item>

                <Form.Item
                  label={t('web.subnetMask')}
                  name="new_mask"
                  rules={dhcpEnabled ? [] : [
                    {
                      required: true,
                      message: t('web.enterSubnetMask'),
                    },
                  ]}
                  extra={t('web.example') + ": 255.255.255.0"}
                >
                  <Input
                    placeholder={t('web.eg') + ": 255.255.255.0"}
                  />
                </Form.Item>

                <Form.Item
                  label={t('web.defaultGateway')}
                  name="router_ip"
                  rules={dhcpEnabled ? [] : [
                    {
                      required: true,
                      message: t('web.enterGateway'),
                    },
                  ]}
                  extra={t('web.example') + ": 192.168.10.1"}
                >
                  <Input
                    placeholder={t('web.eg') + ": 192.168.10.1"}
                  />
                </Form.Item>

                <Form.Item
                  name="dhcpEnabled"
                  valuePropName="checked"
                >
                  <div>
                    <Checkbox onChange={handleDhcpChange}>
                      {t('web.enableDHCP')}
                    </Checkbox>
                    <Tooltip title={t('web.dhcpTooltip')}>
                      <QuestionCircleOutlined style={{ color: '#3498db', marginLeft: 8 }} />
                    </Tooltip>
                  </div>
                </Form.Item>

                <Form.Item>
                  <div className="btns">
                    <Button
                      className='submit-btn btn'
                      icon={<CheckOutlined />}
                      type="primary"
                      htmlType="submit"
                    >
                      {t('web.saveConfig')}
                    </Button>
                    <Button
                      className='reset-btn btn'
                      type="primary"
                      onClick={onReset}
                    >
                      {t('web.reset')}
                    </Button>
                  </div>
                </Form.Item>
              </Form>
            </Card>
          </div>
        </div>

        <div className="right">
          <div className="con-a2">
            <Card
              title={renderCardTitle(
                <ExclamationCircleOutlined style={{ color: '#08c' }} />,
                'web.networkInfo'
              )}
            >
              <div className="list">
                <div className="li">
                  <div className="tit">{t('web.networkStatus')}</div>
                  <div className="text">
                    <div className={'light ' + (info.ip_address ? 'on' : 'off')}></div>
                    <div className={'txt ' + (info.ip_address ? 'on' : 'off')}>
                      {info.ip_address ? t('web.connected') : t('web.disconnected')}
                    </div>
                  </div>
                </div>
                <div className="li">
                  <div className="tit">{t('web.ipAddress')}</div>
                  <div className="text">
                    <div className="txt">{info.ip_address}</div>
                  </div>
                </div>
                <div className="li">
                  <div className="tit">{t('web.subnetMask')}</div>
                  <div className="text">
                    <div className="txt">{info.netmask}</div>
                  </div>
                </div>
                <div className="li">
                  <div className="tit">{t('web.defaultGateway')}</div>
                  <div className="text">
                    <div className="txt">{info.gateway}</div>
                  </div>
                </div>
              </div>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Web;